//
//  LHSearchView.swift
//  LHWeiBo
//
//  Created by snowimba on 16/1/18.
//  Copyright © 2016年 snowimba. All rights reserved.
//

import UIKit

class LHSearchView: UIView {
	
	var markNum = 0
	
	
	private lazy var searchBtn : UIButton = {
		
		let searchBtn : UIButton = UIButton()
		
		searchBtn.addTarget(self, action: "searchBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
		
		searchBtn.setImage(UIImage(named: "searchbar_textfield_search_icon"), forState: UIControlState.Normal)
		
//		searchBtn.sizeToFit()
		
		
		return searchBtn
	}()
	
	class func searchView() -> LHSearchView {
		
		return NSBundle.mainBundle().loadNibNamed("LHSearchView", owner: nil, options: nil).last as! LHSearchView
	}
	
	var searchBtnClickBlack: ((keyWord: String) -> ())?
	
	@objc private func searchBtnClick() {
		
		guard let keyWord = searchField.text else {
			
			return
		}
		
		searchBtnClickBlack? (keyWord: keyWord)
		
	}
	
	override func awakeFromNib() {
		
		super.awakeFromNib()
		
		searchBtn.frame.size = CGSizeMake(self.bounds.height, self.bounds.height)
		searchField.leftView = searchBtn
		searchField.leftViewMode = UITextFieldViewMode.Always
		
		
		
	}
	
	@IBOutlet weak var cancelBtn: UIButton!
	@IBOutlet weak var searchField: UITextField!
	
	@IBOutlet weak var searchFieldTrailing: NSLayoutConstraint!
	@IBAction func cancelBtnClick(sender: AnyObject) {
		
		
		searchFieldTrailing.constant = 0
		
		
		UIView.animateWithDuration(0.25) {() -> Void in
			
			self.searchField.layoutIfNeeded()
			
		}
		searchBtn.enabled = false
		searchField.text = nil
		searchField.endEditing(true)
		
		
	}
	@IBAction func showCanlerBtn(sender: AnyObject) {
		
		
		
		searchBtn.enabled = true
		
		
		searchFieldTrailing.constant = cancelBtn.frame.width + 8
		
		
		UIView.animateWithDuration(0.25) {() -> Void in
			
			self.searchField.layoutIfNeeded()
			
		}
		
	}
	
	/*
	 // Only override drawRect: if you perform custom drawing.
	 // An empty implementation adversely affects performance during animation.
	 override func drawRect(rect: CGRect) {
	 // Drawing code
	 }
	 */
	
}
